package Controller;

import Model.Service;
import Model.ServiceBean;
import Model.Sport;
import Model.SportBean;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/LookService")
public class LookService extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Context context = null;
        HttpSession session = request.getSession();
        try {
            context = new InitialContext();
            Context contextNeeded = (Context) context.lookup("java:comp/env");
            DataSource ds = (DataSource) contextNeeded.lookup("wq");// 获得连接池。
            Connection conn = null;
            ResultSet rs;
            String sql;
            PreparedStatement pstmt;
            conn = ds.getConnection();//获得数据源
            sql = "select * from zhiyuanzhe";
            pstmt =  conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            ServiceBean sb = (ServiceBean) session.getAttribute("serviceBean");
            if(sb==null){
                sb = new ServiceBean();
            }
            ServiceBean temp = new ServiceBean();
            Service d;
            while (rs.next()){
                d = new Service();
                d.setId(rs.getString(1));
                d.setTime(rs.getString(5));
                d.setLocation(rs.getString(6));
                temp.add(d);
            }
            sb.setServices(temp.getServices());
            session.setAttribute("serviceBean",sb);
            conn.close();
            response.sendRedirect("zhiyuanzhe/myService.jsp");
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("加载不成功");
        }
    }
}
